/**
 * 
 */
package com.ivan.utils;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.opensymphony.xwork2.Preparable;
import org.apache.struts2.ServletActionContext;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.ParameterizedType;

public abstract class BaseAction<M> extends ActionSupport implements
		ModelDriven<M>, Preparable {
	
	/**
	 * 
	 */
	private Boolean isAjax = false;

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	/**
	 * 数据模型
	 */
	protected M model;
	/**
	 * 目标视图
	 */
	private String target;
	/**
	 * common的常量
	 */
	public static final String COMMON = "common";
	/**
	 * request对象
	 */
	protected HttpServletRequest request = ServletActionContext.getRequest();
	/**
	 * response对象
	 */
	protected HttpServletResponse response = ServletActionContext.getResponse();

	public BaseAction() {
		super();
		try {
			Class<M> m = (Class<M>) ((ParameterizedType) getClass()
					.getGenericSuperclass()).getActualTypeArguments()[0];
			this.model = m.newInstance();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
	}


	/**
	 * 默认的处理方法
	 */
	public String execute() throws Exception {
		return COMMON;
	}

	/**
	 * 设定目标视图，返回一个通用结果，该通用结果包含一个target的参数
	 * 
	 * @param target
	 *            目标视图
	 * @return 通用配置的结果
	 */
	public String render(String target) {
		setTarget(target);
		return COMMON;
	}

	/**
	 * 将对象转换为json返回
	 * 
	 * @param object
	 *            目标对象
	 * @return
	 */
	public String renderJson(Object object) {
		Struts2Utils.renderJson(object);
		return null;
	}

	/**
	 * 返回json字符串
	 * 
	 * @param jsonString
	 *            目标对象
	 * @return
	 */
	public String renderJsonString(String jsonString) {
		Struts2Utils.render("application/json", jsonString);
		return null;
	}

	/**
	 * @return the target
	 */
	public String getTarget() {
		return target;
	}

	/**
	 * @param target
	 *            the target to set
	 */
	public void setTarget(String target) {
		this.target = target;
	}

	public String getCtx() {
		return ServletActionContext.getRequest().getContextPath();
	}

	@Override
	public M getModel() {
		return model;
	}

	@Override
	public void prepare() throws Exception {
	}

	public Boolean getIsAjax() {
		return isAjax();
	}
	
	/**
	 * 是否为Ajax请求
	 * 
	 * @return
	 */
	private boolean isAjax() {
		String header = request.getHeader("X-Requested-With");
		if (header != null && "XMLHttpRequest".equalsIgnoreCase(header))
			return true;
		else
			return false;
	}

	public void setIsAjax(Boolean isAjax) {
		this.isAjax = isAjax;
	}

	
}
